package com.zerodg.zdutil.util.exception;

/**
 * @program: eroot
 * @description: 全局异常捕获
 * @author: ztz-prince
 * @create:
 * @date:2018-12-22-23:16
 **/

import org.slf4j.LoggerFactory;
//import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("/error")
public class GlobalErrorController implements ErrorController {

    /**
     * 1 ErrorController 接口的默认实现类是abstract：AbstractErrorController
     * 2 AbstractErrorController 的子类 BasicErrorController 才是真正干活儿的实现类（分html、json 两类处理）
     * 3 BasicErrorController 有 private final ErrorProperties errorProperties;属性
     *   BasicErrorController的封装只能将状态码的提示信息返回前台，不能拿到手动抛异常的信息，因此需要实现HandlerExceptionResolver
     */
    private final static String DEFAULT_ERROR_VIEW = "/error";
    private final static  org.slf4j.Logger LOGGER = LoggerFactory.getLogger(GlobalErrorController.class);
    /**
     * ResultBuilder 实现 HandlerExceptionResolver 接口重写public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
     * 通过httpServletRequest.setAttribute("fp.error", e);将Exception放到request中
     * 这种方法的好处是能拿到手动抛异常的信息
     */
    @Resource
    private ResultBuilder resultBuilder;

    /**
     * 针对404的场景
     * @return
     */
    @Override
    public String getErrorPath(){
        return  resultBuilder.getErrorProperties().getPath();
    }

    /**
     * 如果请求头返回的类型是text/html，则返回到错误信息页面
     * @param request
     * @return
     */
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public ModelAndView errorHtml(HttpServletRequest request) {
        return new ModelAndView(DEFAULT_ERROR_VIEW,"errorInfo",resultBuilder.getErrorInfo(request));
    }

    /**
     * 除了text/html的请求头信息，其它都返回json格式
     * @param request 请求对象
     * @return 错误信息字符串
     */
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public ResultInfo error(HttpServletRequest request){
        return resultBuilder.getErrorInfo(request);
    }



}